const JsSHA = require('jssha')

exports.createNonceStr = function () {
  return Math.random().toString(36).substr(2, 15)
}

exports.createTimestamp = function () {
  return parseInt(new Date().getTime() / 1000) + ''
}

var raw = function (args) {
  var keys = Object.keys(args)
  keys = keys.sort()
  var newArgs = {}
  keys.forEach(function (key) {
    newArgs[key.toLowerCase()] = args[key]
  })

  var string = ''
  for (var k in newArgs) {
    string += '&' + k + '=' + newArgs[k]
  }
  string = string.substr(1)
  return string
}

/**
 * @synopsis 签名算法
 */
exports.sign = function (key, data) {
  var ret = Object.assign({
    nonce_str: exports.createNonceStr()
  }, data)
  var string = raw(ret)
  var shaObj = new JsSHA('SHA-256', 'TEXT')
  shaObj.setHMACKey(key, 'TEXT')
  shaObj.update(string)
  shaObj.update('&key=' + key)
  ret.sign = shaObj.getHMAC('HEX')
  return ret
}

exports.signJsapiTicket = function (jsapiTicket, url) {
  var sign = require('./wx/sign.js')
  return sign(jsapiTicket, url)
}

